﻿using System;
using System.Net;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace NetworkTest
{
    //IP辅助类
    public class IPHelper
    {
        //IP正则表达式
        public static string IPRex = @"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$)";

        //请求数
        public static int PingRequestsNumber = 4;
        //本机主机名
        public static string HostName = Dns.GetHostName();
        //获取本机IP列表
        public static IPAddress[] IPAddressList = Dns.GetHostAddresses(HostName);
        //本机IP
        public static string LocalIP = IPAddressList[IPAddressList.Length - 1].ToString();
        //本机IP地址拼接的字符串
        public static string LocalIPs = GetLocalIPs();

        //检查IP地址是否合法
        public static bool IsIP(string ip)
        {
            return new Regex(IPRex).IsMatch(ip);
        }

        //返回IP地址最后一位
        public static string GetLastNumber(string ip)
        {
            //分割IP地址
            string[] ips = ip.Split(new char[] { '.' });
            //返回最后一位
            return ips[3];
        }

        //获取本机IP地址字符串
        public static string GetLocalIPs()
        {
            //
            StringBuilder ipstr = new StringBuilder(60);
            int i = 0;
            //遍历
            foreach (IPAddress ip in IPAddressList)
            {
                //判断是否IPV4
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    //拼接IP地址字符串
                    ipstr.Append(ip.ToString()).Append("  ");
                    i++;
                }
            }
            //返回
            return ipstr.ToString();
        }

        //获取MAC地址
        public static string GetMacList()
        {
            try
            {
                //结果
                string outText = ProcessHelper.Cmd2("arp -a");
                //按行分割,删除空字符串
                string[] strArr = outText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                string[] strArr2 = strArr.Where(s => !string.IsNullOrEmpty(s)).ToArray();
                //结果
                StringBuilder result = new StringBuilder(200);
                //遍历数组
                for (int i = 0; i < strArr2.Length; i++)
                {
                    //跳过0,1,2以及最后一项
                    if (i > 2 && i != strArr2.Length - 1)
                    {
                        string s = strArr2[i];
                        result.Append(s).Append(Environment.NewLine);
                    }
                }

                //返回
                return result.ToString();
            }
            catch
            {
                return "获取Mac地址表失败";
            }
        }
    }
}
